<%-- 
    Document   : ViewIndividual
    Created on : Apr 30, 2013, 2:57:28 PM
    Author     : baumae03
--%>

<%@page import="java.util.ArrayList"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="com.java.FamTree.*"%>
<%@page import="java.util.Calendar" %>
<%@page import="java.util.GregorianCalendar"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%
ArrayList<Field> lastEditFields = new ArrayList<Field>();
Field[] editFields = new Field[8];
// Check to see if we're logged in.
if (session.getAttribute("UserId") == null) {
    response.sendRedirect("index.jsp"); // Send them away if they're not logged in.
}
int userId = (Integer)session.getAttribute("UserId");

if(request.getParameter("PersonId") == null) {
    out.println("You must specify a PersonId in order to get information back.");
}

boolean IsAdmin = false;
if(session.getAttribute("IsAdmin") != null) {
	
    IsAdmin = (Boolean)session.getAttribute("IsAdmin") ? true : false;
}

int PersonId = -1;
try {
   PersonId = Integer.parseInt(request.getParameter("PersonId"));
} catch (NumberFormatException ex) {
    PersonId = -1;
}

if(PersonId == -1) {
    response.sendError(400, "Invalid PersonId");
}


try{
    Class.forName("com.mysql.jdbc.Driver");
} catch (java.lang.ClassNotFoundException e) {
    System.err.println("ClassNotFoundException: " + e);
}

	/* 
	* First thing is to get all the last edited by users and dates
	*/
	Connection con3 = null;
	try { 
		con3 = DriverManager.getConnection("jdbc:mysql://webdev.cs.uwosh.edu:4381/severa24?zeroDateTimeBehavior=convertToNull", "severa24", "d450224"); 
		PreparedStatement selectFields = con3.prepareStatement("SELECT f.FieldId, u.Username, MAX(LastEditDate) FROM Field f INNER JOIN User u ON u.UserId = f.UserId Where Person = ? GROUP BY f.FieldId");
		selectFields.setInt(1, PersonId);
		
		ResultSet fieldeSet = selectFields.executeQuery();
		while(fieldeSet.next()) {
	        Field f = new Field();
	        f.FieldId = fieldeSet.getInt(1);
	        f.Username = fieldeSet.getString(2);
	        if(fieldeSet.getLong(3) == 0){
	        	f.LastEditDate = null;
	        }
	        else{
	        	f.LastEditDate = fieldeSet.getString(3);
	        	f.LastEditDate = f.LastEditDate.substring(0, 10);
	        }
	        lastEditFields.add(f);
	    } 
		
	} catch (SQLException ex) { 
	    System.err.println(ex);
	} finally {
	    if (con3 != null ) {
	        try {
	            con3.close();
	        } catch (SQLException ex) {
	            System.err.println(ex);
	        }
	    }
	}	
	
	/*
	* Now loop through the last edit fields and add them to the actual list
	*/
	for(int i = 0; i < editFields.length; i ++){
		for(Field f : lastEditFields){
			if(f.FieldId == i + 7){
				editFields[i] = f;
			}
		}
	}

Connection con = null;
Person person = null;
ArrayList<Person> children = new ArrayList<Person>();
ArrayList<Person> spouses = new ArrayList<Person>();
ArrayList<Event> events = new ArrayList<Event>();
try {
    con = DriverManager.getConnection("jdbc:mysql://webdev.cs.uwosh.edu:4381/severa24?zeroDateTimeBehavior=convertToNull", "severa24", "d450224");
    PreparedStatement selectPerson = con.prepareStatement(
            "SELECT PersonId, Bio, BirthDate, BirthPlace, Name, Gender, LastKnownAddress, DeathDate, DeathPlace " +
            "FROM Person WHERE PersonId = ?");

    selectPerson.setInt(1, PersonId);

    ResultSet rst = selectPerson.executeQuery();

    if(rst.first()) {
        person = new Person();
        person.PersonId = rst.getInt(1);
        person.Bio = rst.getString(2);
        person.BirthDate = rst.getString(3);
        person.BirthPlace = rst.getString(4);
        person.Name = rst.getString(5);
        person.Gender = rst.getBoolean(6);
        person.LastKnownAddress = rst.getString(7);
        person.DeathDate = rst.getString(8);
        person.DeathPlace = rst.getString(9);
    } else {
        // If we don't find the person we're looking for, throw an error.
        response.sendError(400, "Invalid PersonId");
    }
                                  
} catch (SQLException ex) { 
    System.err.println(ex); 
} finally {
    if (con != null ) {
        try {
            con.close();
        } catch (SQLException ex) {
            System.err.println(ex);
        }
    }
}


if (person != null) {
    try {
        con = DriverManager.getConnection("jdbc:mysql://webdev.cs.uwosh.edu:4381/severa24?zeroDateTimeBehavior=convertToNull", "severa24", "d450224");
        PreparedStatement selectChildren = con.prepareStatement(
                "SELECT cp.PersonId, cp.Name, Parent FROM Child LEFT JOIN Person cp on Child.Child = cp.PersonId WHERE " + 
                "Child.Parent = ?");
        selectChildren.setInt(1, PersonId);
        
        ResultSet rst = selectChildren.executeQuery();
        
        while(rst.next()) {
            Person child = new Person();
            child.PersonId = rst.getInt(1);
            child.Name = rst.getString(2);
            child.ParentId = rst.getInt(3);
            children.add(child);
        }
        
        // Grab the events
        PreparedStatement selectEvents = con.prepareStatement(
                "SELECT Event.EventId, EventType.EventName AS 'EventType', Event.EventDate, Event.EventPlace " + 
                "FROM Relationship LEFT JOIN Event ON Relationship.EventId = Event.EventId " +
                "LEFT JOIN EventType ON Event.EventTypeId = EventType.EventTypeId " + 
                "WHERE Relationship.Husband = ? OR Relationship.Wife = ?");
        selectEvents.setInt(1, PersonId);
        selectEvents.setInt(2, PersonId);
        ResultSet eventsRst = selectEvents.executeQuery();
        while(eventsRst.next()) {
            events.add(new Event(eventsRst.getInt(1), eventsRst.getString(2), eventsRst.getString(3), eventsRst.getString(4)));
        }
    } catch (SQLException ex) {
        System.err.println(ex);
    } finally {
        if (con != null) {
            try{
                con.close();
            } catch (SQLException ex) {
                System.err.println(ex);
            }
        }
    }
}

/*
*	grab all permissions that this user has for this individual
*/
	int[] fieldIds = new int[]{7,8,9,10,11,12,13,14,15,16};
	boolean[] permissions = new boolean[]{false,false,false,false,false,false,false,false,false,false, false};
	ArrayList<Field> permissionFields = new ArrayList<Field>();
	if (person != null) {
		try {
	        con = DriverManager.getConnection("jdbc:mysql://webdev.cs.uwosh.edu:4381/severa24?zeroDateTimeBehavior=convertToNull", "severa24", "d450224");
	        PreparedStatement selectPermissions = con.prepareStatement("SELECT FieldId, LastEditDate FROM Field WHERE Person = ? AND UserId = ?");
	        selectPermissions.setInt(1, PersonId);
	        selectPermissions.setInt(2, userId);
	        
	        ResultSet rst = selectPermissions.executeQuery();
	        
	        int count = 0;
	        while(rst.next()) {
	        	Field f = new Field();
	        	f.FieldId = rst.getInt(1);
	        	f.LastEditDate = rst.getString(2);
	        	permissionFields.add(f);
	        }
	        
	        for(Field f : permissionFields){
	        	permissions[f.FieldId - 7] = true;
	        }
	        
	        
	    } catch (SQLException ex) {
	        System.err.println(ex);
	    } finally {
	        if (con != null) {
	            try{
	                con.close();
	            } catch (SQLException ex) {
	                System.err.println(ex);
	            }
	        }
	    }
	}


%>


<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Viewing Individual: <% out.print(person.Name); %></title>
    </head>
    <body>
    <Div style="text-align:right;background-color:#F0F0F0;" id="TopMenuBar" >
	<%
		out.print("<span id='WelcomSpan'>Welcome " + session.getAttribute("Username") + "  </span>");
		out.print("<a href='index.jsp'><button>Logout</button></a>");
		if((Boolean)session.getAttribute("IsAdmin")){
			out.print("<a href='Admin.jsp'><button>Admin</button></a>");
	                out.print("<a href='AddPerson.jsp'><button>Add Person</button></a>");
		}
	%>
	</Div>
    
         <center>
            <h1>Individual: <% out.print(person.Name); %></h1>
            <br/><br/>
            <h3>Personal Information</h3>
            <form name="MyForm" method=post action="${pageContext.request.contextPath}/UpdatePersonInformation.jsp">
            <input style="display:none" name="UserId" value='<% out.print(userId); %>'/>
            <input style="display:none" name="PersonId" value='<% out.print(PersonId); %>'/>
            <table>
                	<tr>
                		<th>Person ID</th>
                    	<td><input value='<% out.print(person.PersonId); %>' disabled='disabled' /></td>
                	<tr>
                	<tr>
                		<th>Bio</th>
                    	<td><input style="display:none" value='<% out.print(person.Bio); %>'  name="Bio1"/><textarea cols="37" <% out.print((permissions[0] || IsAdmin) ? "" : "readonly"); %> name="Bio"><% out.print(person.Bio); %></textarea></td><td>Last Edited: <% out.print(editFields[0] == null || editFields[0].LastEditDate == null ? "N/A" : editFields[0].Username + " - " + editFields[0].LastEditDate); %></td>
                   	</tr>
                    <tr>
                    	<th>Birth Date (yyyy-mm-dd)</th>
                    	<td><input style="display:none" value='<% out.print(person.BirthDate); %>'  name="BirthDate1"/><input size='50' value='<% out.print(person.BirthDate); %>' <% out.print((permissions[1] || IsAdmin) ? "" : "readonly"); %> name="BirthDate"/></td><td>Last Edited: <% out.print(editFields[1] == null || editFields[1].LastEditDate == null ? "N/A" : editFields[1].Username + " - " + editFields[1].LastEditDate); %> </td>
                    </tr>
                    <tr>
                    	<th>Birth Place</th>
                    	<td><input style="display:none" value='<% out.print(person.BirthPlace); %>'  name="BirthPlace1"/><input size='50' value='<% out.print(person.BirthPlace); %>' <% out.print((permissions[2] || IsAdmin) ? "" : "readonly"); %> name="BirthPlace"/></td><td>Last Edited: <% out.print(editFields[2] == null || editFields[2].LastEditDate == null ? "N/A" : editFields[2].Username + " - " + editFields[2].LastEditDate); %> </td>
                    </tr>
                    <tr>
                    	<th>Name</th>
                    	<td><input style="display:none" value='<% out.print(person.Name); %>'  name="Name1"/><input size='50' value='<% out.print(person.Name); %>' <% out.print((permissions[3] || IsAdmin) ? "" : "readonly"); %> name="Name"/></td><td>Last Edited: <% out.print(editFields[3] == null || editFields[3].LastEditDate == null ? "N/A" : editFields[3].Username + " - " + editFields[3].LastEditDate); %> </td>
                    </tr>
                    <tr>
                    	<th>Gender</th>
                    	<td><input style="display:none" value='<% out.print(person.Gender ? "1" : "0"); %>'  name="Gender1"/><select width="250px" value='<% out.print(person.Gender); %>' <% out.print((permissions[4] || IsAdmin) ? "" : "readonly"); %> name="Gender"> <option value="1" <% out.print(person.Gender? "selected='selected'" : ""); %>>Male</option><option value="0" <% out.print(person.Gender? "" : "selected='selected'"); %>>Female</option> </select></td><td>Last Edited: <% out.print(editFields[4] == null || editFields[4].LastEditDate == null ? "N/A" : editFields[4].Username + " - " + editFields[4].LastEditDate); %> </td>
                    </tr>
                    <tr>
                    	<th>Last Known Address</th>
                    	<td><input style="display:none" value='<% out.print(person.LastKnownAddress); %>'  name="LastKnownAddress1"/><input size='50' value='<% out.print(person.LastKnownAddress); %>' <% out.print((permissions[5] || IsAdmin) ? "" : "readonly"); %> name="LastKnownAddress"/></td><td>Last Edited: <% out.print(editFields[5] == null || editFields[5].LastEditDate == null ? "N/A" : editFields[5].Username + " - " + editFields[5].LastEditDate); %> </td>
                    </tr>
                    <tr>
                    	<th>Death Date (yyyy-mm-dd)</th>
                    	<td><input style="display:none" value='<% out.print(person.DeathDate); %>'  name="DeathDate1"/><input size='50' value='<% out.print(person.DeathDate); %>' <% out.print((permissions[6] || IsAdmin) ? "" : "readonly"); %> name="DeathDate"/></td><td>Last Edited: <% out.print(editFields[6] == null || editFields[6].LastEditDate == null ? "N/A" : editFields[6].Username + " - " + editFields[6].LastEditDate); %> </td>
                    </tr>
                    <tr>
                    	<th>Death Place</th>
                    	<td><input style="display:none" value='<% out.print(person.DeathPlace); %>'  name="DeathPlace1"/><input size='50' value='<% out.print(person.DeathPlace); %>' <% out.print((permissions[7] || IsAdmin) ? "" : "readonly"); %> name="DeathPlace"/></td><td>Last Edited: <% out.print(editFields[7] == null || editFields[7].LastEditDate == null ? "N/A" : editFields[7].Username + " - " + editFields[7].LastEditDate); %></td>
                	</tr>
            </table>
            <div style="text-align:center">
				<button class="submit" type="submit" name="sub" value="Save Information">Save Permissions</button>
			</div>
			</form>
			<script type="text/javascript" src="Scripts/jquery-1.8.3.js"></script>
			<script type="text/javascript">
				$(document).ready(function () {
					var on = false;
					$('#ShowNewChildButton').click(function(){
						if(!on){
							$("#HideShowNewChild").css({'display' : ''});
							on = true;
						}else{
							$("#HideShowNewChild").css({'display' : 'none'});
							on = false;
						}
					});
				});
			</script>
			<% if(IsAdmin){ %>
			<div id="newChildContainer" >
			</br>
			</br>
				<button Id="ShowNewChildButton">Add New Child</button>
				<div id="HideShowNewChild" style="display:none">
				<form name="MyForm" method=post action="${pageContext.request.contextPath}/AddChild.jsp">
					<input style="display:none" name='PersonId'  value='<% out.print(PersonId); %>' />
					PersonId: <input name="ChildId" /><button class="submit" type="submit" name="sub" value="Add Child">Submit</button>
				</form>
				</div>
			</div>
			<% } %>
			
            <%
                // We don't want to display this children section if they have no children!
                if (true) {
            %>
            <h3>Children</h3>
            <table>
                <tr>
                    <th>Person ID</th>
                    <th>Name</th>
                    <th>&nbsp;</th>
                </tr>
                <%
                    for(int i = 0; i < children.size(); i++) {
                        %>
                        <form name="MyForm" method=post action="${pageContext.request.contextPath}/RemoveChild.jsp">
                        <tr>
                            <td>
                                <a href="${pageContext.request.contextPath}/ViewIndividual.jsp?PersonId=<%out.print(children.get(i).PersonId);%>"><%out.print(children.get(i).PersonId);%></a>
                            	<input style="display:none" name='ParentId'  value='<% out.print(children.get(i).ParentId); %>' />
                            	<input style="display:none" name='ChildId'  value='<% out.print(children.get(i).PersonId); %>' />
                            </td>
                            <td>
                                <% out.print(children.get(i).Name); %>
                            </td>
                            <% if(IsAdmin || permissions[7]){ %>
                            <td>
                            	<button class="submit" type="submit" name="sub" value="Remove Child">Remove</button>
                            </td>
                             <% } %>
                        </tr>
                        </form>
                    <%
                    }
                %>
            </table>
            <%
                       }
            %>
            
            <%
                if (!events.isEmpty()) {      
            %>
            <h3>Events</h3>
            <table>
                <tr>
                    <th>
                        Event ID
                    </th>
                    <th>
                        Event Type
                    </th>
                    <th>
                        Event Date
                    </th>
                    <th>
                        Event Place
                    </th>
                </tr>
                <%
                    for(int i = 0; i < events.size(); i++) {
                %>
                        <tr>
                            <td>
                                <% out.print(events.get(i).EventId); %>
                            </td>
                            <td>
                                <% out.print(events.get(i).EventType); %>
                            </td>
                            <td>
                                <% out.print(events.get(i).EventDate); %>
                            </td>
                            <td>
                                <% out.print(events.get(i).EventPlace); %>
                            </td>
                        </tr>
                <%
                }
                %>
            </table>
            <%
                       }
            %>
                    
            
            
            
         </center>
    </body>
</html>
